package com.sqllog.admin.auth.config;

import com.sqllog.admin.auth.domain.Power;
import com.sqllog.admin.auth.domain.User;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


/**
 * 自定义 Security 权限注解实现
 *
 * @author chennengcheng
 * @date 2022-01-21 17:02
 * @remark
 */

@Component
public class PermissionSupport implements PermissionEvaluator {


    /**
     * Describe: 自定义 Security 权限认证 @hasPermission
     * Param: Authentication
     * Return Boolean
     */
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        User securityUserDetails = (User) authentication.getPrincipal();
        if ("admin".equals(securityUserDetails.getUsername())) {
            return true;
        }
        List<Power> powerList = securityUserDetails.getPowerList();
        Set<String> permissions = new HashSet<>();
        for (Power sysPower : powerList) {
            permissions.add(sysPower.getPowerCode());
        }
        return permissions.contains(permission);
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
